import numpy as np
import pandas as pd


# 熵值法确定指标权重
def get_weight_by_entropy(proportion_df):
    rows = proportion_df.shape[0]
    cols = proportion_df.shape[1]
    # 先算K值
    k = 1 / np.log(rows)
    # ------老方法------
    djs = []
    for column in proportion_df.columns:
        hj = 0
        for pij in proportion_df[column]:
            hj += pij * np.log(pij)
        dj = 1 - ((-k) * hj)
        djs.append(dj)
    print('-----------djs-----------')
    print(djs)
    # ------老方法------

    h_j = (-k) * np.array(
        [sum([pij * np.log(pij) for pij in proportion_df[column]]) for column in proportion_df.columns])
    print('-----------h_j-----------')
    print(h_j)
    h_js = pd.Series(h_j, index=proportion_df.columns, name='指标的熵值')
    print('-----------h_js-----------')
    print(h_js)
    # 求差异系数
    df_djs = pd.Series(1 - h_j, index=proportion_df.columns, name='差异系数')
    print('-----------差异系数-----------')
    print(df_djs)
    # 计算指标权重
    weights = df_djs / sum(df_djs)
    weights.name = '熵值法确定指标权重'

    print('-----------熵值法确定指标权重-----------')
    print(weights)

    return weights
